package com.strive.village.security;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.strive.village.common.Result;
import com.strive.village.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * @Author: strivePeng
 * @CreateTime: 2024年04月19日
 * @Description: 登陆成功处理器
 **/

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    JwtUtils jwtUtils;

    @Value("${ip.api.url}")
    private String IP_API_URL;

    /**
     * 实现接口方法
     * 登陆成功后生成jwt将信息存储到请求头
     *
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();
        // 生成jwt，并放置到请求头中
        String jwt = jwtUtils.generateToken(authentication.getName());
        response.setHeader(jwtUtils.getHeader(), jwt);

        WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
        String ipAddress = details.getRemoteAddress();

        RestTemplate restTemplate = new RestTemplate();
        String url = IP_API_URL + ipAddress;
        Map<String, Object> location = restTemplate.getForObject(url, Map.class);
        LocalDateTime loginTime = LocalDateTime.now();

        // 格式化时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedLoginTime = loginTime.format(formatter);

        Result result = Result.success(MapUtil.builder()
                .put("loginTime", formattedLoginTime)
                .put("location", location)
                .put("ipAddress", ipAddress)
                .build());

        outputStream.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));

        outputStream.flush();
        outputStream.close();
    }
}
